package com.mkjb.controller;

import com.mkjb.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

/**
 * Created by DingJie on 2017/2/19.
 */
@Controller
public class LoginController {
    /**
     * 进入登录界面
     * @param model
     * @return 登录界面
     */
    @RequestMapping(value = "/login.htm", method = RequestMethod.GET)
    public String loginIndex(Model model) {
        model.addAttribute("user", new User());
        return "login";
    }

    /**
     * 登录请求方法
     * @param user 登录用户
     * @param bindingResult //验证
     * @param redirectAttributes 返回信息
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Valid User user, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        try {
            if (bindingResult.hasErrors()) {
                return "login";
            }
            if (!user.isEnable()) {
                redirectAttributes.addFlashAttribute("message", "用户已被禁用");
                return "login";
            }
            //使用权限工具进行用户登录，登录成功后跳到shiro配置的successUrl中，与下面的return没什么关系！
            SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
            return "redirect:/index";
        } catch (AuthenticationException e) {
            redirectAttributes.addFlashAttribute("message", "用户名或密码错误");
            return "redirect:/login";
        }
    }

    /**
     * 退出
     * @param redirectAttributes 返回信息
     * @return 登录首页
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(RedirectAttributes redirectAttributes) {
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        SecurityUtils.getSubject().logout();
        redirectAttributes.addFlashAttribute("message", "您已安全退出");
        return "redirect:/login";
    }

    @RequestMapping("/403")
    public String unauthorizedRole() {
        return "/403";
    }
    @RequestMapping("/admin/index.htm")
    public String index() {
        return "index";
    }

}
